﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Jinjia.Approve.Common.Extensions
{
    /// <summary>
    ///  HttpClient扩展类
    /// </summary>
    public static class HttpClientExtensions
    {
        /// <summary>
        /// 根据Url地址Get请求返回实体
        /// </summary>
        /// <typeparam name="T">泛型类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="decompressionMethods">解压缩方式，默认：GZip</param>
        /// <param name="accept">客户端希望接收的数据类型</param>
        /// <param name="headers">头部信息</param>
        /// <param name="delegate">自定义委托</param>
        /// <param name="httpClientName">HttpClient注入的名称，此名称用于HttpClientFactory创建HttpClient使用</param>
        /// <returns>返回请求结果和状态结果</returns>
        public static async Task<(T result, HttpStatusCode code)> GetAsync<T>(this HttpClient client,
            string url,
            IDictionary<string, string> parameters) where T : class
        {
            (T result, HttpStatusCode code) result;
            var response = await client.GetAsync(url + parameters.ToUrl("?", false, false));

            if (response.IsSuccessStatusCode)
                result = ((await response.Content.ReadAsStringAsync()).ToObject<T>(), response.StatusCode);
            else
                result = (default(T), response.StatusCode);

            return result;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input"></param>
        /// <param name="requestUri"></param>
        /// <returns></returns>
        public static async Task<(R result, HttpStatusCode code)> PostAsync<T, R>(this HttpClient client, T input, string requestUri)
            where T : class
            where R : class
        {
            return await client.PostAsync<R>(input.ToJson(), requestUri);
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <typeparam name="R"></typeparam>
        /// <param name="input"></param>
        /// <param name="requestUri"></param>
        /// <returns></returns>
        public static async Task<(R result, HttpStatusCode code)> PostAsync<R>(this HttpClient client, string input, string requestUri) where R : class
        {
            var requestContent = new StringContent(input, Encoding.UTF8, "application/json-patch+json");
            var response = await client.PostAsync(requestUri, requestContent);
            var res = await response.Content.ReadAsStringAsync();
            return (res.ToObject<R>(), response.StatusCode);
        }
    }
}
